package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"github.com/mojocn/base64Captcha"
	"github.com/monoculum/formam/v3"
	"html/template"
	"iris_product/common"
	"iris_product/datamodels"
	"iris_product/encrypt"
	"iris_product/services"
	"net/http"
	"strconv"
	"time"
)

var store = base64Captcha.DefaultMemStore

type UserController struct {
	UserService services.IUserService
	Ctx iris.Context
}

func (u *UserController) GetRegister() mvc.View {
	return mvc.View{
		Name: "user/register.html",
	}
}

func (u *UserController) GetLogin() mvc.View {

	driverMath := base64Captcha.DriverMath{
		Height:          80,
		Width:           240,
		NoiseCount:      4,
		ShowLineOptions: 0,
		BgColor:         nil,
		Fonts:           nil,
	}
	// new一个验证吗对象
	captcha := common.NewCaptcha(driverMath.ConvertFonts(), store)
	// 生成验证码
	captchaId, b64s, err := captcha.Generate()
	if err != nil {
		u.Ctx.Redirect("/user/error")
		return mvc.View{}
	}

	u.Ctx.SetCookie(&http.Cookie{Name: "captchaCode",Value: captchaId,Expires: time.Now().Add(time.Minute * 5)})
	//u.Sess.Set("captchaCode",captchaId)
	return mvc.View{
		Name: "user/login.html",
		Data: iris.Map{
			"captchaCode":template.URL(b64s),
		},
	}
}

func (u *UserController) PostLogin() {
	// 获取post参数
	u.Ctx.Request().ParseForm()
	decoder := formam.NewDecoder(&formam.DecoderOptions{TagName: "miaosha",IgnoreUnknownKeys:true})
	user := &datamodels.User{}
	err := decoder.Decode(u.Ctx.Request().PostForm,user)
	if err != nil {
		common.Log.Error("解析参数错误:" + err.Error())
		u.Ctx.Redirect("/user/error")
		return
	}

	// 获取验证码值
	captchaAnswer := u.Ctx.Request().FormValue("captchaAnswer")

	captchaCode := u.Ctx.GetCookie("captchaCode")
	common.Log.Debug("获取到的验证码信息为:captchaCode:" + captchaCode + " 答案:" + captchaAnswer)
	if !store.Verify(captchaCode,captchaAnswer,true) {
		// 验证码验证不通过
		common.Log.Debug("验证码验证不通过")
		u.Ctx.Redirect("/user/error")
		return
	}

	// 验证密码
	user, err = u.UserService.IsLoginSuccess(user.UserName, user.Password)
	if err != nil {
		common.Log.Error("密码错误:" + err.Error())
		u.Ctx.Redirect("/user/error")
		return
	}

	// 设置cookie
	//u.Sess.Set("uid",user.ID)
	u.Ctx.SetCookie(&http.Cookie{Name: "uid",Value: strconv.FormatInt(user.ID, 10),Path: "/"})
	userJsonByte,_ := json.Marshal(user)
	fmt.Println(string(userJsonByte))
	//uidByte := []byte(strconv.FormatInt(user.ID,10))
	userStr,err := encrypt.EnPwdCode(userJsonByte)
	if err != nil {
		u.Ctx.Application().Logger().Error("加密失败:" + err.Error())
	}

	fmt.Println(userStr)
	u.Ctx.SetCookie(&http.Cookie{Name: "sign",Value: userStr,Path: "/"})
	u.Ctx.SetCookie(&http.Cookie{Name: "test",Value: "1234567890",Path: "/"})

	u.Ctx.Redirect("/product")
	return

}


func (u *UserController) PostRegister() {
	u.Ctx.Request().ParseForm()
	decoder := formam.NewDecoder(&formam.DecoderOptions{TagName: "miaosha"})
	user := &datamodels.User{}
	err := decoder.Decode(u.Ctx.Request().PostForm, user)
	if err != nil {
		common.Log.Error("解析错误:" + err.Error())
		return
	}

	// 获取用户IP
	user.Ip = u.Ctx.RemoteAddr()

	// 验证
	errStr := u.UserService.ValidateUser(user)
	if errStr != "" {
		common.Log.Error("参数传递错误:" + errStr)
		u.Ctx.Redirect("/user/error")
		return
	}
	//fmt.Println(user)
	_,err = u.UserService.AddUser(user)
	if err != nil {
		u.Ctx.Redirect("/user/error")
		return
	}


	u.Ctx.Redirect("/user/login")
	return


}

